// Copyright (C) 2025 Focus Media Holding Ltd. All Rights Reserved.

package cn.pacerx.running.wx.service;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

import cn.pacerx.running.core.viewobject.OrderClauseVo;
import cn.pacerx.running.db.dao.ActivityMapper;
import cn.pacerx.running.db.domain.Activity;
import cn.pacerx.running.db.domain.User;
import cn.pacerx.running.db.enums.ActivityStatusEnum;
import cn.pacerx.running.db.enums.UserActivityStatusEnum;
import cn.pacerx.running.db.service.UserService;
import cn.pacerx.running.wx.dto.JoinActivityDto;
import cn.pacerx.running.wx.vo.ActivityPagedVo;
import cn.pacerx.running.wx.vo.UserActivityPagedVo;
import io.mybatis.mapper.example.Example;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import cn.pacerx.running.core.util.ResponseUtil;
import cn.pacerx.running.db.dao.UserActivityMapper;
import cn.pacerx.running.db.domain.UserActivity;
import cn.pacerx.running.wx.dto.UserActivityDto;
import cn.pacerx.running.wx.util.UserUtil;
import lombok.RequiredArgsConstructor;

import static com.github.pagehelper.page.PageMethod.startPage;

/**
 * UserActivityService
 *
 * @since 2025-06-13
 */
@Service
@RequiredArgsConstructor
public class UserActivityService {
    private final UserActivityMapper userActivityMapper;
    private final ActivityMapper activityMapper;
    private final UserService userService;

    public List<UserActivityDto> getList(Set<Long> activityIds) {
        Long userId = UserUtil.getUserId();
        List<UserActivity> activityList = userActivityMapper.wrapper()
                .eq(UserActivity::getUserId, userId)
                .in(UserActivity::getActivityId, activityIds)
                .list();

        if (CollectionUtils.isNotEmpty(activityList)) {
            return activityList.stream()
                    .map(this::toDto)
                    .collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    public UserActivityDto getDetail(Long activityId) {
        Long userId = UserUtil.getUserId();
        return userActivityMapper.wrapper()
                .eq(UserActivity::getUserId, userId)
                .eq(UserActivity::getActivityId, activityId)
                .one()
                .map(this::toDto)
                .orElse(null);
    }

    /**
     * 根据活动创建人，获取历史记录
     * @param activityUserId 获取创建id
     */
    public List<UserActivityDto> getHistoryList(Long activityUserId, int limit) {
        List<UserActivity> activityList = userActivityMapper.wrapper()
                .eq(UserActivity::getActivityUserId, activityUserId)
                .orderByDesc(UserActivity::getAddTime)
                .top(limit);

        if (CollectionUtils.isNotEmpty(activityList)) {
            return activityList.stream()
                    .map(this::toDto)
                    .collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    public Object getListByPage() {
        Long userId = UserUtil.getUserId();
        List<UserActivityDto> userActivityDtos = userActivityMapper.wrapper()
                .ne(UserActivity::getUserId, userId)
                .list()
                .stream()
                .map(this::toDto)
                .collect(Collectors.toList());
        return ResponseUtil.okList(userActivityDtos);
    }

    private UserActivityDto toDto(UserActivity userActivity) {
        UserActivityDto activityDto = new UserActivityDto();
        BeanUtils.copyProperties(userActivity, activityDto);
        return activityDto;
    }

    public Object save(JoinActivityDto joinActivityDto) {
        Long activityId = joinActivityDto.getActivityId();
        Optional<Activity> activityOptional = activityMapper.selectByPrimaryKey(activityId);
        if (activityOptional.isEmpty()) {
            return ResponseUtil.fail(400, "活动不存在");
        }
        Activity activity = activityOptional.get();
        if (activity.getStatus() == ActivityStatusEnum.ENDED) {
            return ResponseUtil.fail(400, "活动已结束");
        }
        if (activity.getStatus() == ActivityStatusEnum.LOCKED) {
            return ResponseUtil.fail(400, "活动已锁定");
        }
        Long userId = UserUtil.getUserId();
        if (activity.getUserId().equals(userId)) {
            return ResponseUtil.fail(400, "非法报名");
        }
        UserActivityDto userActivityDto = getDetail(activityId);
        if (userActivityDto!= null) {
            return ResponseUtil.fail(400, "已报名");
        }
        // 获取当前报名用户信息
        User user = userService.findById(userId.intValue());
        if (BooleanUtils.isTrue(user.getDeleted())) {
            return ResponseUtil.fail(400, "无效用户");
        }
        if (user.getStatus() != 0) {
            return ResponseUtil.fail(400, "用户异常");
        }
        // todo：必须要是实名用户才能报名
        UserActivity userActivity = new UserActivity();
        userActivity.setId(null);
        userActivity.setUserId(userId);
        userActivity.setNickname(user.getNickname());
        userActivity.setAvatar(user.getAvatar());
        userActivity.setActivityId(activityId);
        userActivity.setActivityUserId(activity.getUserId());
        userActivity.setRemark(joinActivityDto.getRemark());
        userActivity.setStatus(UserActivityStatusEnum.JOINED);
        userActivityMapper.insert(userActivity);
        return ResponseUtil.ok(userActivity.getId());
    }

    public Object delete(Long id) {
        // 检查活动状态
        Optional<Activity> activityOptional = activityMapper.selectByPrimaryKey(id);
        if (activityOptional.isEmpty()) {
            return ResponseUtil.fail(400, "活动不存在");
        }
        Activity activity = activityOptional.get();
        if (activity.getStatus() == ActivityStatusEnum.ENDED) {
            return ResponseUtil.fail(400, "活动已结束");
        }
        LocalDate exitDate = activity.getStartDate().minusDays(1L);
        if (!LocalDate.now().isBefore(exitDate) || activity.getStatus() == ActivityStatusEnum.LOCKED) {
            return ResponseUtil.fail(400, "活动已锁定");
        }
        if (activity.getStatus() == ActivityStatusEnum.OBSOLETED) {
            return ResponseUtil.fail(400, "活动已废弃");
        }
        // 判断报名活动是否存在
        UserActivity userActivity = new UserActivity();
        userActivity.setActivityId(id);
        userActivity.setUserId(UserUtil.getUserId());
        Optional<UserActivity> userActivityOptional = userActivityMapper.selectOne(userActivity);
        if (userActivityOptional.isEmpty()) {
            return ResponseUtil.fail(400, "未报名");
        }
        userActivity = userActivityOptional.get();
        userActivityMapper.deleteByPrimaryKey(userActivity.getId());
        return ResponseUtil.ok();
    }

    public List<UserActivity> getMinePagedList(ActivityPagedVo request) {
        startPage(request.getPage(), request.getLimit());
        Example<UserActivity> example = new Example<>();
        Example.Criteria<UserActivity> criteria = example.createCriteria();
        // 构建查询条件
        criteria.andEqualTo(UserActivity::getStatus, ActivityStatusEnum.PENDING);
        // 创建人
        Long userId = UserUtil.getUserId();
        criteria.andEqualTo(UserActivity::getUserId, userId);
        // 排序条件
        List<OrderClauseVo> orderByClause = request.getOrderByClause();
        if (CollectionUtils.isNotEmpty(orderByClause)) {
            orderByClause.forEach(orderClause -> example.orderBy(" order by "
                    + orderClause.getCol() + (orderClause.isAsc() ? Example.Order.ASC : Example.Order.DESC)));
        }
        return userActivityMapper.selectByExample(example);
    }

}
